package com.example.infrastructure.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.entity.Menu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MenuMapper extends BaseMapper<Menu> {

    /**
     * 查询用户权限列表
     */
    @Select("SELECT DISTINCT m.permission FROM sys_menu m " +
            "LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id " +
            "LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} " +
            "AND m.type = 2 " +
            "AND m.status = '1' " +
            "AND m.deleted = 0")
    List<String> selectPermissionsByUserId(@Param("userId") Long userId);

    /**
     * 查询角色的菜单ID列表
     */
    @Select("SELECT menu_id FROM sys_role_menu WHERE role_id = #{roleId}")
    List<Long> selectMenuIdsByRoleId(@Param("roleId") Long roleId);

    /**
     * 查询用户的菜单列表
     */
    @Select("SELECT DISTINCT m.* FROM sys_menu m " +
            "LEFT JOIN sys_role_menu rm ON m.id = rm.menu_id " +
            "LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} " +
            "AND m.status = '1' " +
            "AND m.deleted = 0 " +
            "ORDER BY m.sort")
    List<Menu> selectMenusByUserId(@Param("userId") Long userId);

    /**
     * 统计使用该菜单的角色数量
     */
    @Select("SELECT COUNT(*) FROM sys_role_menu WHERE menu_id = #{menuId}")
    int countRoleMenuByMenuId(@Param("menuId") Long menuId);

    /**
     * 插入角色菜单关系
     */
    void insertRoleMenus(@Param("roleId") Long roleId, @Param("menuIds") List<Long> menuIds);

    /**
     * 删除角色菜单关系
     */
    void deleteRoleMenus(@Param("roleId") Long roleId);
} 